package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.AdClient;
import com.robot.admin.pojo.client.Ad;
import com.robot.admin.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 广告模块
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/ad")
public class AdController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private AdClient adClient;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * ad表type 广告类型 0-图片 1-视频
     */
    private final String adTypeImage = "0";
    private final String adTypeVideo = "1";
    /**
     * ad表position 广告位置 0-首页广告 1-回调广告
     */
    private final String adPositionHome = "0";
    private final String adPositionCallback = "1";

    /**
     * 广告列表-条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findAdBySearch/{page}/{size}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result findAdBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(adClient.thirdFindAdBySearch(searchMap, page, size)));
    }

    /**
     * 根据ID查询广告详情
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "findAdById/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result findAdById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId() + ", ad'id=" + id);
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Ad adInDb = JSON.parseObject(adClient.thirdFindAdById(id), Ad.class);
        logger.info("adInDb=" + adInDb);
        String message = checkPojo(adInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, adInDb);
    }

    /**
     * 增加广告
     *
     * @param ad
     */
    @RequestMapping(value = "addAd", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result addAd(@RequestBody Ad ad) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("ad=" + ad);
        if (ad.getTitle() == null || "".equals(ad.getTitle())) {
            return new Result(StatusCode.ERROR_AD_TITLE_REQUIRED);
        }
        if (ad.getType() == null || "".equals(ad.getType())) {
            return new Result(StatusCode.ERROR_AD_TYPE_REQUIRED);
        }
        if (!adTypeImage.equals(ad.getType()) && !adTypeVideo.equals(ad.getType())) {
            return new Result(StatusCode.ERROR_AD_TYPE_INVALID);
        }
        if (ad.getPosition() == null || "".equals(ad.getPosition())) {
            return new Result(StatusCode.ERROR_AD_POSITION_REQUIRED);
        }
        if (!adPositionHome.equals(ad.getPosition()) && !adPositionCallback.equals(ad.getPosition())) {
            return new Result(StatusCode.ERROR_AD_POSITION_INVALID);
        }
        if (ad.getImageUrl() == null || "".equals(ad.getImageUrl())) {
            return new Result(StatusCode.ERROR_AD_IMAGE_URL_REQUIRED);
        }

        if (!checkUtil.checkImage(ad.getImageUrl())) {
            return new Result(StatusCode.ERROR, "请输入正确格式的广告图片");
        }

        logger.info("status=" + ad.getStatus());
        /**
         * ad表status 状态0-禁用 1-启用
         */
        String adStatusDisable = "0";
        if (ad.getStatus() != null && adStatusDisable.equals(ad.getStatus())) {
            ad.setStatus(adStatusDisable);
        } else {
            String adStatusEnable = "1";
            ad.setStatus(adStatusEnable);
        }

        adClient.thirdAddAdByAd(JSON.toJSONString(ad));
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 修改广告
     *
     * @param ad
     */
    @RequestMapping(value = "updateAd/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result updateAd(@RequestBody Ad ad, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("ad=" + ad);
        Ad adInDb = JSON.parseObject(adClient.thirdFindAdById(id), Ad.class);
        logger.info("adInDb=" + adInDb);
        String message = checkPojo(adInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        if (ad.getImageUrl() != null && !"".equals(ad.getImageUrl())) {

            if (!checkUtil.checkImage(ad.getImageUrl())) {
                return new Result(StatusCode.ERROR, "请输入正确格式的广告图片");
            }
        }
        adInDb = updatePojo(ad, adInDb);
        adClient.thirdUpdateAdByAd(JSON.toJSONString(adInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除广告
     *
     * @param id
     */
    @RequestMapping(value = "deleteAdById/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result deleteAdById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Ad adInDb = JSON.parseObject(adClient.thirdFindAdById(id), Ad.class);
        logger.info("adInDb=" + adInDb);
        String message = checkPojo(adInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        adInDb.setDeletedAt(LocalDateTime.now());
        adClient.thirdUpdateAdByAd(JSON.toJSONString(adInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }


    @RequestMapping(value = "/findAdsByStatusToIndex/{status}", method = RequestMethod.GET)
    public Result thirdFindAdsToIndex(@PathVariable String status) {
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(adClient.thirdFindAdsToIndex(status)));
    }

    @RequestMapping(value = "/findAdsByPositionAndStatus/{position}/{status}", method = RequestMethod.GET)
    public Result findTop2ByPositionAndStatusOrderByCreatedAt(@PathVariable String position, @PathVariable String status) {
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(adClient.thirdFindTop2ByPositionAndStatusOrderByCreatedAt(position, status)));
    }

    /**
     * 检查实体类是否存在
     *
     * @param ad
     * @return
     */
    public String checkPojo(Ad ad) {
        if (ad == null) {
            return ("该条广告不存在");
        }
        if (ad.getDeletedAt() != null) {
            return ("该条广告已被删除");
        }
        return "";
    }

    /**
     * update时更新实体类
     *
     * @param ad
     * @param adInDb
     * @return
     */
    public Ad updatePojo(Ad ad, Ad adInDb) {
        if (ad.getTitle() != null && !"".equals(ad.getTitle())) {
            adInDb.setTitle(ad.getTitle());
        }
        if (adTypeImage.equals(ad.getType()) || adTypeVideo.equals(ad.getType())) {
            adInDb.setType(ad.getType());
        }
        if (adPositionHome.equals(ad.getPosition()) || adPositionCallback.equals(ad.getPosition())) {
            adInDb.setPosition(ad.getPosition());
        }

        if (ad.getUrl() != null && !"".equals(ad.getUrl())) {
            adInDb.setUrl(ad.getUrl());
        }
        if (ad.getAreaList() != null && !"".equals(ad.getAreaList())) {
            adInDb.setAreaList(ad.getAreaList());
        }
        if (ad.getSort() != null && !"".equals(ad.getSort())) {
            adInDb.setSort(ad.getSort());
        }
        adInDb.setUpdatedAt(LocalDateTime.now());
        return adInDb;
    }
}







